import { ChatRequestParams, ChatResponse, ChatMessage } from '@/types/fetch';
import { streamFetch } from './fetch';

// 聊天API基础URL
const CHAT_API_BASE = '/api/client/chat';

// 发送聊天消息（流式）
export const sendChatMessageStream = async (
  params: ChatRequestParams,
  onMessage: (data: any) => void,
  abortController: AbortController
) => {
  try {
    const response = await streamFetch({
      url: `${CHAT_API_BASE}/completions`,
      data: {
        ...params,
        stream: true,
        detail: true,
        contentId: params.contentId
      },
      onMessage,
      abortCtrl: abortController
    });
    
    return response;
  } catch (error) {
    console.error('流式聊天请求失败:', error);
    throw error;
  }
};

// 发送聊天消息（非流式）
export const sendChatMessage = async (params: ChatRequestParams): Promise<ChatResponse> => {
  try {
    const response = await streamFetch({
      url: `${CHAT_API_BASE}/completions`,
      data: {
        ...params,
        stream: false,
        detail: false
      },
      onMessage: (data: any) => {
        console.log('Stream message:', data);
      },
      abortCtrl: new AbortController()
    });
    console.log(response,'response');
    
    return response as unknown as ChatResponse;
  } catch (error) {
    console.error('聊天请求失败:', error);
    throw error;
  }
};


// 获取聊天会话列表
export const getChatSessionList = async (params: { search?: string } = {}) => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/list`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('获取聊天会话列表失败:', error);
    throw error;
  }
};

// 获取聊天会话详情
export const getChatSessionDetail = async (chatId: string) => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/detail`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ chatId })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('获取聊天会话详情失败:', error);
    throw error;
  }
};

// 创建新的聊天会话
export const createChatSession = async (params: { title?: string } = {}) => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('创建聊天会话失败:', error);
    throw error;
  }
};

// 更新聊天会话
export const updateChatSession = async (chatId: string, params: { title?: string; isPinned?: boolean }) => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/update`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ chatId, ...params })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('更新聊天会话失败:', error);
    throw error;
  }
};

// 删除聊天会话
export const deleteChatSession = async (chatId: string) => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/delete`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ chatId })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('删除聊天会话失败:', error);
    throw error;
  }
};

// 清空所有聊天记录
export const clearAllChatHistory = async () => {
  try {
    const response = await fetch(`${CHAT_API_BASE}/sessions/clear`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({})
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('清空聊天记录失败:', error);
    throw error;
  }
};

// 工具函数：将消息转换为API格式
export const formatMessagesForAPI = (messages: ChatMessage[]) => {
  return messages.map(msg => ({
    role: msg.role,
    content: msg.content
  }));
};

// 工具函数：生成新的消息ID
export const generateMessageId = () => {
  return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
};

// 工具函数：生成新的聊天ID（临时）
export const generateChatId = () => {
  return `temp_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
};
